/*
 * @Author: ✨Fireflx 
 * @Date: 2022-02-15 10:21:31 
 * @Last Modified by: ✨Fireflx
 * @Last Modified time: 2022-02-16 13:01:54
 */

const multer = require('koa-multer')
const path = require('path')
const fs = require('fs')

const router = require('koa-router')()

router.prefix('/upload')

const storage = multer.diskStorage({
// const upload = multer({
    destination: function (req,file,cb) {
        const date = new Date()
        let day = date.getDate();
        day = day < 10 ? '0'+day : day;
        let month = date.getMonth()+1;
        month = month < 10 ? '0'+month : month;

        const dir = './public/uploads/'+
        date.getFullYear()+month+day;

        //判断目录是否存在
        if(!fs.existsSync(dir)){
            fs.mkdirSync(dir,{
                recursive:true
            })
        }
        cb(null, dir)
    },
    filename:function(req,file,cb){
        //设置上传文件名
        const filename = file.originalname.split('.')[0].substring(0,3) + 
        '-' + Date.now() +
        path.extname(file.originalname);
        cb(null,filename)
    }
})

const upload = multer({
    storage
})

//头像
router.post('/img',upload.single('kelin-file'),async ctx=>{
    let {path} = ctx.req.file
    path = ctx.origin + '' +path.replace('public','')
    ctx.body = {path}
})
//文章图片
router.post("/editor/img",upload.single('editor-file'),
    async ctx => {
        let {path} = ctx.req.file;
        path = ctx.origin+''+path.replace('public','')
        ctx.body = {
            errno:0,
            data:[{
                url:path,
                alt:'',
                href:''
            }]
        }
})

module.exports = router